<template>
  <view>
    <!-- 吸顶效果 -->
    <view class="search-box">
      <uni-search-bar @confirm="search" @input="input" :radius="100" cancelButton="none" bgColor="#e5e5e5">
      </uni-search-bar>
    </view>

    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length!==0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item)">
        <view class="goods-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="paperclip" size="16"></uni-icons>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="18" @click="clean"></uni-icons>
      </view>
      <!-- 列表区 -->
      <view class="history-list">
        <uni-tag :text="item2" v-for="(item2,i2) in histories" :key="i2" @click="gotoGoodsList(item2)"></uni-tag>
      </view>

    </view>

  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        //延时器关键词
        kw: '',
        //这是搜索的结果列表
        searchResults: [],
        //搜索历史数据
        historyList: [],
      };
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    methods: {


      //input输入事件的处理函数
      input(e) {
        // console.log(e);\

        clearTimeout(this.timer)

        this.timer = setTimeout(() => {
          // console.log(e);
          this.kw = e

          this.getSearchList()
        }, 500)
      },
      //根据搜索关键词,搜索商品建议列表
      async getSearchList() {
        //判断关键词是否为空
        if (this.kw.length === 0) {
          this.searchResults = []
          return
        }
        const {
          data: res
        } = await uni.$http.get('https://api-ugo-web.itheima.net/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResults = res.message

        this.saveSearchHistory()
      },
      //前往商品详情页
      gotoDetail(item) {
        // console.log(item.goods_id);
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      saveSearchHistory() {
        // this.historyList.push(this.kw)

        //解决搜索关键字重复问题
        // 1. 将 Array 数组转化为 Set 对象
        const set = new Set(this.historyList)
        // 2. 调用 Set 对象的 delete 方法，移除对应的元素
        set.delete(this.kw)
        // 3. 调用 Set 对象的 add 方法，向 Set 中添加元素
        set.add(this.kw)
        // 4. 将 Set 对象转化为 Array 数组
        this.historyList = [...set]
        // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },

      //清空历史记录的按钮
      clean() {
        this.historyList = [],
          uni.setStorageSync('kw', '[]')
      },

      // 搜索历史标签点击事件前往 商品详情页
      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?query=' + kw
        })
      }


    },
    //计算属性
    computed: {
      histories() {
        return [...this.historyList].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 1;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      display: flex;
      //侧轴剧中
      align-items: center;
      //主轴两端贴边对齐
      justify-content: space-between;
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #dadada;

      .goods-name {
        //文本不允许换行 单行显示
        white-space: nowrap;
        //文本超出隐藏
        overflow: hidden;
        //超出部分用...显示
        text-overflow: ellipsis;
      }
    }
  }

  .history-box {
    padding: 0px 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #d6d6d6;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>
